package com.wondertek.service.sdk.iotdh.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
@Slf4j
public class CodeEncryption {

	public String convertDevCode(String devCode, String sk) {
		String converted = null;
		try {
			converted = PlatFormAESUtil.getEncryptStr(devCode, sk, "86E2DB6D77B5E9CD");
		} catch (Exception ex) {
			log.error("Ase256加密 出错");
		}

		return converted;
	}

	/**
	 * 平台加解密内部类
	 */
		public static class PlatFormAESUtil {
		// 以下代码提取到公共区域
		public static byte[] cbcEncrypt(byte[] srcData, byte[] key, byte[] iv) throws Exception {
			SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
			Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, keySpec, new IvParameterSpec(iv));
			byte[] encData = cipher.doFinal(srcData);
			return encData;
		}

		public static byte[] getKeyBytes(String aesTextKey) {
			return DigestUtils.md5Hex(aesTextKey.toUpperCase()).toUpperCase().getBytes();
		}

		public static String getEncryptStr(String str, String aesTextKey, String iv) throws Exception {
			byte[] keys = getKeyBytes(aesTextKey);
			byte[] encbt = cbcEncrypt(str.getBytes(), keys, iv.getBytes());
			return java.util.Base64.getEncoder().encodeToString(encbt);
		}
	}
}